package com.haha.community.intercept;

import com.haha.community.entity.LoginTicket;
import com.haha.community.entity.User;
import com.haha.community.service.UserService;
import com.haha.community.util.CookieUtil;
import com.haha.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class MyIntercept implements HandlerInterceptor {
    @Autowired
    UserService userService;
    @Autowired
    HostHolder hostHolder;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //其他情况下默认没有登陆，不做处理
        String value = CookieUtil.getCookieValueFromRequest(request, "ticket");
        if (value!=null){
            LoginTicket loginTicket = userService.selectLoginTicketByTicket(value);
            if (loginTicket!=null&&loginTicket.getStatus()==0&&loginTicket.getExpired().after(new Date())){
                //说明此时ticket有效
                User user = userService.findUserById(loginTicket.getUserId());
                //将user存到线程中,制作一个小的工具类进行使用
                hostHolder.set(user);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.get();
        if (user!=null){
            modelAndView.addObject("user",user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
    }
}
